package com.dlwx.parttimetalent.views;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.github.jdsjlzx.recyclerview.LRecyclerView;

/**
 * Created by Administrator on 2017/12/19.
 */

public class MyGridLayoutManager extends GridLayoutManager {

    private LRecyclerView recyclerView;
    private int spanCount;

    // RecyclerView高度随Item自适应
    public MyGridLayoutManager(Context context, int spanCount, LRecyclerView recyclerView) {
        super(context, spanCount);
        this.recyclerView = recyclerView;
        this.spanCount=spanCount;
    }

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
        int measuredWidth = recyclerView.getMeasuredWidth();
        int measuredHeight = recyclerView.getMeasuredHeight();
        int myMeasureHeight = 0;
        int count = state.getItemCount();
        for (int i = 0; i < count; i++) {
            View view = recycler.getViewForPosition(i);
            if (view != null) {
                if (myMeasureHeight < measuredHeight && i % spanCount == 0) {
                    RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
                    int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                            getPaddingLeft() + getPaddingRight(), p.width);
                    int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                            getPaddingTop() + getPaddingBottom(), p.height);
                    view.measure(childWidthSpec, childHeightSpec);
                    myMeasureHeight += view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                }
                recycler.recycleView(view);
            }
        }
//                    Log.i("Height", "" + Math.min(measuredHeight, myMeasureHeight));
        setMeasuredDimension(measuredWidth, Math.min(measuredHeight, myMeasureHeight));
    }
}
